/*
 * Copyright (C) 2010 Cyril Mottier (http://www.cyrilmottier.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hktf.corelib;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.hktf.corelib.core.ActivityManager;
import com.hktf.corelib.jsonbean.UserInfo;
import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.Config;
import com.zhy.autolayout.config.AutoLayoutConifg;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Define various methods that should be overridden in order to style your
 * application.
 *
 * @author Cyril Mottier
 */
public class BaseApplication extends Application {
    private static Handler mainHandler;
    private static int mainTid;// 记录主线程Tid

    private static Handler handlerManager;

    public static void setHandlerManager(Handler handlerManager) {
        BaseApplication.handlerManager = handlerManager;
    }

    public static Handler getHandlerManager() {
        return handlerManager;
    }


    /**
     * Used for receiving low memory system notification. You should definitely
     * use it in order to clear caches and not important data every time the
     * system needs memory.
     *
     * @author Cyril Mottier
     * @see BaseApplication#registerOnLowMemoryListener(OnLowMemoryListener)
     * @see BaseApplication#unregisterOnLowMemoryListener(OnLowMemoryListener)
     */
    public static interface OnLowMemoryListener {

        /**
         * Callback to be invoked when the system needs memory.
         */
        public void onLowMemoryReceived();
    }

    private static final int CORE_POOL_SIZE = 5;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "GreenDroid thread #"
                    + mCount.getAndIncrement());
        }
    };

    private ExecutorService mExecutorService;

    private ArrayList<WeakReference<OnLowMemoryListener>> mLowMemoryListeners;

    private ActivityManager activityManager;

    private static Context context;

    boolean isDataBind = false;
    private Intent dataServiceIntent;

    public static boolean isBluetoothConn = false;

    public static boolean isUsbConn = false;

    private boolean isDemo = false;

    private String currentDevie = "";

    /**
     * 存储 动态 功能路径
     */
    private static String CANActiveType_path = "";
    private int mConnectStatus = 0;
    private int controlType = 0;

    private boolean bChatLogin = false;


    public boolean isbChatLogin() {
        return bChatLogin;
    }

    public void setbChatLogin(boolean bChatLogin) {
        this.bChatLogin = bChatLogin;
    }

    public int getControlType() {
        return controlType;
    }

    public void setControlType(int controlType) {
        this.controlType = controlType;
    }


    public String getCurrentDevie() {
        return currentDevie;
    }

    public void setCurrentDevie(String currentDevie) {
        this.currentDevie = currentDevie;
    }

    public static Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public ActivityManager getActivityManager() {
        return activityManager;
    }

    public void setActivityManager(ActivityManager activityManager) {
        this.activityManager = activityManager;
    }

    /**
     * @hide
     */
    public BaseApplication() {
        mLowMemoryListeners = new ArrayList<WeakReference<OnLowMemoryListener>>();
    }

    /**
     * Return an ExecutorService (global to the entire application) that may be
     * used by clients when running long tasks in the background.
     *
     * @return An ExecutorService to used when processing long running tasks
     */
    public ExecutorService getExecutor() {
        if (mExecutorService == null) {
            mExecutorService = Executors.newFixedThreadPool(CORE_POOL_SIZE,
                    sThreadFactory);
        }
        return mExecutorService;
    }

    /**
     * Return the class of the home Activity. The home Activity is the main
     * entrance point of your application. This is usually where the
     * dashboard/general menu is displayed.
     *
     * @return The Class of the home Activity
     */
    public Class<?> getHomeActivityClass() {
        return null;
    }

    /**
     * Each application may have an "application intent" which will be used when
     * the user clicked on the application button.
     *
     * @return The main application Intent (may be null if you don't want to use
     * the main application Intent feature)
     */
    public Intent getMainApplicationIntent() {
        return null;
    }

    /**
     * Add a new listener to registered {@link OnLowMemoryListener}.
     *
     * @param listener The listener to unregister
     * @see OnLowMemoryListener
     */
    public void registerOnLowMemoryListener(OnLowMemoryListener listener) {
        if (listener != null) {
            mLowMemoryListeners.add(new WeakReference<OnLowMemoryListener>(
                    listener));
        }
    }

    /**
     * Remove a previously registered listener
     *
     * @param listener The listener to unregister
     * @see OnLowMemoryListener
     */
    public void unregisterOnLowMemoryListener(OnLowMemoryListener listener) {
        if (listener != null) {
            int i = 0;
            while (i < mLowMemoryListeners.size()) {
                final OnLowMemoryListener l = mLowMemoryListeners.get(i).get();
                if (l == null || l == listener) {
                    mLowMemoryListeners.remove(i);
                } else {
                    i++;
                }
            }
        }
    }



    /*
     * (non Javadoc) <p>Title: onCreate</p> <p>Description: </p>
     *
     * @see android.app.Application#onCreate()
     */
    @Override
    public void onCreate() {
        context = this;
        mainHandler = new Handler();
        mainTid = android.os.Process.myTid();
        super.onCreate();

        AutoLayoutConifg.getInstance().useDeviceSize();
        // 初始化自定义Activity管理器
        activityManager = ActivityManager.getScreenManager();

    }


    public static int getMainTid() {
        return mainTid;
    }

    public static Handler getMainHandler() {
        return mainHandler;
    }

    public void initService() {
        initUserInfo();
        Config.ISVIPUSER = isVIPUser();
        // hxSDKHelper.onInit(applicationContext);
        // 异常崩溃异常信息保存
        // CrashHandler handler = CrashHandler.getInstance();
        // handler.init(getApplicationContext());
        // Thread.setDefaultUncaughtExceptionHandler(handler);
    }
    public static void initUserInfo(){
        CommUtils.getUserInfo();
        Config.ISVIPUSER = isVIPUser();
    }


    /**
     * 判断是否是VIP用户
     *
     * @return
     */
    public static boolean isVIPUser() {
        boolean result = false;
        return result;
    }

    /**
     * 获取数据库 中的用户数据
     */
    public static UserInfo getUserInfo() {
        UserInfo userinfo = null;
//        UserInfoImpl userInfoImpl = new UserInfoImpl(this);
//        List<UserInfo> data = userInfoImpl.findAll();
//        if (data != null) {
//            userinfo = data.get(0);
//        }
//        RoleUserInfo roleUserInfo = MMKVUtils.getObj(KEYS.USERINFO, RoleUserInfo.class);
//        Config.userInfo=roleUserInfo;
        return userinfo;
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        int i = 0;
        while (i < mLowMemoryListeners.size()) {
            final OnLowMemoryListener listener = mLowMemoryListeners.get(i)
                    .get();
            if (listener == null) {
                mLowMemoryListeners.remove(i);
            } else {
                listener.onLowMemoryReceived();
                i++;
            }
        }
    }

    public boolean isUsbConn() {
        return isUsbConn;
    }

    public void setUsbConn(boolean isUsbConn) {
        this.isUsbConn = isUsbConn;
    }

    public boolean isBluetoothConn() {
        return isBluetoothConn;
    }

    public void setBluetoothConn(boolean isBluetoothConn) {
        this.isBluetoothConn = isBluetoothConn;
    }

    public boolean isDataBind() {
        return isDataBind;
    }

    public void setDataBind(boolean isDataBind) {
        this.isDataBind = isDataBind;
    }

    public Intent getDataServiceIntent() {
        return dataServiceIntent;
    }

    public void setDataServiceIntent(Intent dataServiceIntent) {
        this.dataServiceIntent = dataServiceIntent;
    }

    public static String getCANActiveType_path() {
        return CANActiveType_path;
    }

    public static void setCANActiveType_path(String cANActiveType_path) {
        CANActiveType_path = cANActiveType_path;
    }

    public int getmConnectStatus() {
        return mConnectStatus;
    }


}
